package com.ericom.webapp.action;

import java.util.List;

import com.ericom.model.Stock;
import com.ericom.service.GenericManager;

public class StockAction extends BaseAction {
	private GenericManager<Stock, Long> stockManager;
	private List stocks;
	private Stock stock;
	private Long id;

	public Stock getStock() {
		return stock;
	}

	public void setStock(Stock stock) {
		this.stock = stock;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public void setStockManager(GenericManager<Stock, Long> stockManager) {
		this.stockManager = stockManager;
	}

	public String list() {
		stocks = stockManager.getAll();
		return SUCCESS;
	}

	public List getStocks() {
		return stocks;
	}

	public String delete() {
		stockManager.remove(stock.getId());
		this.saveMessage(getText("stock.deleted"));
		return this.SUCCESS;
	}

	public String edit() {
		if (id != null) {
			stock = stockManager.get(id);
		} else {
			stock = new Stock();
		}
		return this.SUCCESS;
	}

	public String save() throws Exception {
		if (this.cancel != null) {
			return this.CANCEL;
		}
		if (this.delete != null) {
			return this.delete();
		}

		boolean isNew = (stock.getId() == null);
		stock = stockManager.save(stock);

		String key = (isNew) ? "stock.added" : "stock.updated";
		this.saveMessage(getText(key));

		if (!isNew) {
			return this.INPUT;
		} else {
			return this.SUCCESS;
		}
	}
}
